package org.smart4j.aopdemo.jdkdynamic;

import org.smart4j.aopdemo.simple.Greeting;
import org.smart4j.aopdemo.simple.GreetingImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {

    private Object target;


    public DynamicProxy(Object target) {
        this.target = target;
    }

    public  <T> T getProxyInstance(){
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(target,args);
        after();
        return result;
    }



    public void before(){
        System.out.println(" before Hello ");
    }

    public void after(){
        System.out.println(" after Hello");
    }

    public static void main(String[] args){
        DynamicProxy dynamicProxy = new DynamicProxy(new GreetingImpl());
        Greeting greeting = dynamicProxy.getProxyInstance();
        greeting.sayHello("liuzx");
    }
}
